<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/home">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        center
        :closable="false"
      >
      </el-alert>
      <el-steps
        :space="200"
        :active="parseInt(activeIndex)"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addRef"
        label-width="100px"
        label-position="top"
      >
        <!-- @tab-click="handleClick" -->
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model.trim="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader
                :options="cateList"
                :props="cascaderProps"
                v-model="selectedKeys"
                @change="onHandleChange"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in manyTabData"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="item1"
                  v-for="(item1, i) in item.attr_vals"
                  :key="i"
                  border
                  size="small"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in onlyTabData"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!--  -->
            <!-- :on-error="handleError" -->
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
              :headers="headObj"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="add" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%"
      ><img :src="previewPath" alt="" style="width: 100%;"
    /></el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        goods_cat: '',
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      addRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        selectedKeys: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      cateList: [],
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      manyTabData: [],
      onlyTabData: [],
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      headObj: {
        Authorization: sessionStorage.getItem('token')
      },
      previewPath: '',
      previewVisible: false,
      selectedKeys: []
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    onHandleChange() {
      // console.log(this.selectedKeys)
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
      }
    },
    beforeTabLeave(active, old) {
      // console.log(old, active)
      if (old === '0' && this.selectedKeys.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
      return true
    },
    tabClicked() {
      // console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        // 商品参数面板
        this.getParamsData('many')
      } else if (this.activeIndex === '2') {
        // 商品属性面板
        this.getParamsData('only')
      }
    },
    async getParamsData(sel) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: sel }
        }
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      if (sel === 'many') {
        res.data.forEach(item => {
          if (item.attr_vals) {
            item.attr_vals = item.attr_vals.split(' ')
          } else {
            item.attr_vals = []
          }
        })
        this.manyTabData = res.data
      } else {
        this.onlyTabData = res.data
      }
    },
    handlePreview(file) {
      console.log(file)
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    handleRemove(file, fileList) {
      console.log('on-remove', file, fileList)
      const filePath = file.response.data.tmp_path
      const index = this.addForm.pics.findIndex(x => x.pic === filePath)
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm.pics)
    },
    handleSuccess(res, file, fileList) {
      console.log('on-success', res, file, fileList)
      if (res.meta.status !== 200) {
        return
      }
      const picInfo = { pic: res.data.tmp_path }
      this.addForm.pics.push(picInfo)
      console.log(this.addForm.pics)
    },
    /* handleError(err, file, fileList) {
      console.log('on-error', err)
    } */
    async add() {
      const result = await this.$refs.addRef.validate().catch(e => e)
      if (!result || this.selectedKeys.length !== 3) {
        this.$message.error('请填写必要的表单项')
        return
      }
      // console.log('验证成功')
      this.addForm.goods_cat = this.selectedKeys.join(',')
      const many = this.manyTabData.map(item => {
        return {
          attr_id: item.attr_id,
          attr_value: item.attr_vals.join(',')
        }
      })
      const only = this.onlyTabData.map(item => {
        return {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
      })
      this.addForm.attrs = [...many, ...only]
      console.log(this.addForm)
      const { data: res } = await this.$http.post('goods', this.addForm)
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
      this.$message.success('添加商品成功')
      this.$router.push('/goods')
    }
  },
  computed: {
    // 当前选中的三级分类ID
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  justify-content: center;
}

.el-checkbox {
  margin: 0 !important;
  margin-right: 10px !important;
}

.add {
  margin-top: 15px;
}
</style>
